package com.zlkj.pro.core.util;

import com.zlkj.pro.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.THE_APPLE_SERVER_IS_ABNORMAL;

/**
 * @author 孙铭泽
 * @date 2022/10/27
 * @time 16:28
 */
@Slf4j
public class IosVerifyUtil {

    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    /**
     * 沙盒环境
     */
    private static final String URL_SANDBOX = "https://sandbox.itunes.apple.com/verifyReceipt";
    /**
     * 生产环境
     */
    private static final String URL_VERIFY = "https://buy.itunes.apple.com/verifyReceipt";

    /**
     * 苹果服务器验证
     *
     * @param receipt 账单
     * @return 返回结果
     */
    public static String buyAppVerify(String receipt) {
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(URL_SANDBOX);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setRequestMethod("POST");
            // conn.setRequestProperty("content-type", "text/json");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());
            //拼成固定的格式传给平台
            String str = "{\"receipt-data\":\"" + receipt + "\"}";
            hurlBufOus.write(str.getBytes());
            hurlBufOus.flush();
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception ex) {
            log.error("苹果服务器异常", ex);
            throw new BusinessException(THE_APPLE_SERVER_IS_ABNORMAL);
        }
    }

    /**
     * 用BASE64加密
     */
    public static String getBase64(String str) {
        byte[] b = str.getBytes();
        return new sun.misc.BASE64Encoder().encode(b);
    }
}
